package cn.lzx.user.service.impl;

import cn.lzx.basic.excpetion.BusinessExcpetion;
import cn.lzx.basic.service.impl.BaseServiceImpl;
import cn.lzx.basic.util.AjaxResult;
import cn.lzx.basic.util.MD5Utils;
import cn.lzx.user.domain.LoginDto;
import cn.lzx.user.domain.Logininfo;
import cn.lzx.user.mapper.LogininfoMapper;
import cn.lzx.user.service.ILogininfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *  LogininfoService实现类
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public AjaxResult accountLogin(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String username = loginDto.getUsername();
        Integer loginType = loginDto.getLoginType();
        //空值判断
        if (StringUtils.isEmpty(password)||
                StringUtils.isEmpty(username)||
                StringUtils.isEmpty(loginType)){
            throw new BusinessExcpetion("请输入正确的信息");
        }
        //根据传入的信息跟数据库比对
        Logininfo logininfo = logininfoMapper.findByUsername(loginDto);
        if (logininfo==null){
            throw new BusinessExcpetion("用户名或密码错误");
        }
        //1.2.用户名或密码【加密加盐】校验
        //数据库中加密加盐的密码
        String DbMd5Pwd = logininfo.getPassword();
        String Md5Pwd = MD5Utils.encrypByMd5(password + logininfo.getSalt());
        if (!DbMd5Pwd.equals(Md5Pwd)){
            throw new BusinessExcpetion("用户名或密码错误");
        }
        //1.3.状态校验 - 启用，禁用
        if(!logininfo.getDisable()){
            throw new BusinessExcpetion("你的账号被冻结，请联系管理员");
        }
        //获取token
        String token  = UUID.randomUUID().toString();
        //2.将token和登录信息对象 保存在 redis 30分钟有效
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //3.使用Map将token和登录对象绑定到AjaxResult的resultObj中响应给前端
        //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return AjaxResult.me().setResultObj(map);
    }
}
